// const session = require("express-session");
const dbConfig = require("../util/dbConfig");
const sql = require("../util/sqlCode");
require("../util/chalk"); //log color
require("../util/clearCode"); //定时清除验证码
//下载
getFiles = async (req, res, next) => {
  const { file, directory } = req.query;
  if (!file)
    return next({ msg: "下载文件名不能为空", err: "File name is not defined" });
  // 文件路径与名称，用户下载的文件名称
  res.download(`./res/${directory || "images"}/${file}`, file, function (err) {
    console.log(logred(err || "文件传输"));
    if (err && err.status === 404) next({ msg: "下载失败,未找到该文件", err });
  });
};
//获取分类 /
getCate = async (req, res, next) => {
  let getAll = await dbConfig.SySqlConnect(sql.getCateSelectSQL);
  if (getAll.hasOwnProperty("err")) return next(getAll);
  res.send({
    list: getAll,
  });
};
//获取指定id的数据
getPostCate = async (req, res, next) => {
  let { id } = req.query;
  var sqlArr = id;
  const getWhereSQL = sql.getPostCateSelectIdSQL;
  let getWhere = await dbConfig.SySqlConnect(getWhereSQL, sqlArr);
  res.send({
    list: getWhere,
  });
};

//存放onlyVal和count的数组
//服务启动后第一次计数器会在凌晨4点执行，执行完毕重置计数器时间为24小时，循环执行
//发送算术验证码
getCode = async (req, res, next) => {
  // console.log(req.cookies);
  // res.cookie('coName','pzk',{maxAge:1000*10,expires: 1000 * 100}) //设置cookie
  // console.log(req.cookies);
  // req.session.seName = "sepzk"; //设置请求 添加session成员
  let min = Math.ceil(Math.random() * 10);
  let max = Math.ceil(Math.random() * 10);
  let codeObj = {
    1: [min + max, "+"],
    2: [min + max, "+"],
    3: [min + max, "+"],
    4: [min + max, "+"],
    5: [min - max, "-"],
    6: [min - max, "-"],
    7: [min - max, "-"],
    8: [min * max, "*"],
    9: [min * max, "*"],
    10: [min * max, "*"],
  };
  let count = codeObj[min];
  let onlyVal = Math.random().toFixed(5) * 1e5 + min * 1e5;
  codeList[onlyVal] = count[0];
  console.log(codeList);
  res.send({
    code: min + count[1] + max,
    onlyVal,
  });
  //插入空值，用于统计访问量数据
  const if_ins = await dbConfig.SySqlConnect(sql.getCodeInsertSQL);
  if (if_ins.hasOwnProperty("err")) return console.log(if_ins);
};
// 登录 判断验证码、用户名密码是否正确
proveCode = async (req, res, next) => {
  // 重定向，若session成员值为假则跳转到首页
  // if (!req.session.seName) return res.redirect("/");
  let { count, onlyVal, name, password } = req.query;
  if (!codeList.hasOwnProperty(onlyVal))
    return next({ msg: `未找到验证码标识:${onlyVal}`, status: 502 });
  if (codeList[onlyVal] !== +count) return next({ msg: "验证码错误" });
  delete codeList[onlyVal];
  let sqlArr = [name, password];
  const shorSESQL = sql.proveCodeSelectNPSQL;
  const login = await dbConfig.SySqlConnect(shorSESQL, sqlArr);
  if (login.hasOwnProperty("err")) return next(login);
  if (login.length > 0) return res.send({ msg: "登录成功", user: login });
  const shorSNSQL = sql.proveCodeSelectNameSQL;
  let login_name = await dbConfig.SySqlConnect(shorSNSQL, name);
  if (login_name.hasOwnProperty("err")) return next(login_name);
  return next({ msg: login_name.length > 0 ? "密码错误" : "用户名错误" });
};

//  注册
registered = async (req, res, next) => {
  let { name, password } = req.query;
  // 参数为空或参数名请求错误时
  if (!req.query.name || !req.query.password)
    return next({
      msg: "用户名或密码为空",
      err: "或请求参数填写有误",
    });
  let sqlArrCheck = [name];
  const getCheckSQL = sql.registeredSelectNameSQL;
  let getCheck = await dbConfig.SySqlConnect(getCheckSQL, sqlArrCheck);
  if (getCheck.hasOwnProperty("err")) return next(getCheck);
  if (getCheck.length > 0) return next({ msg: "用户名已存在:", name });
  let sqlArr = [name, password, "新用户默认值"];
  let getreg = await dbConfig.SySqlConnect(sql.registeredInsertUserSQL, sqlArr);
  if (getreg.hasOwnProperty("err")) return next(getreg);
  res.send({
    insertId: `注册成功!欢迎${name}成为第${getreg.insertId}位用户`,
    code: 1,
    user: getreg,
  });
  countRows++; //users_table行数+1
};
// 退出登录
dropOut = (req, res, next) => {
  // req.session.seName = ''
  req.session.cookie.maxAge = 0;
  res.redirect("/");
  console.log(logsucc("退出登录,回到首页"));
};

// 编辑用户信息
editUser = async (req, res, next) => {
  let { name, newName, password, test } = req.query;
  let getCheck = await dbConfig.SySqlConnect(sql.editUserSelectNameSQL, name);
  if (getCheck.hasOwnProperty("err")) return next(getCheck);
  if (getCheck.length <= 0) return next({ msg: "没有找到该用户信息" });
  if (!password && !newName && !test)
    return res.send({ user: getCheck, msg: "用户信息" });
  let getNewCheck = newName
    ? await dbConfig.SySqlConnect(sql.editUserSelectNameSQL, newName)
    : [];
  if (getNewCheck.hasOwnProperty("err")) return next(getNewCheck);
  if (getNewCheck.length !== 0) return next({ msg: "用户名重复" });
  let defaName = newName || getCheck[0].name;
  let defaPassword = password || getCheck[0].password;
  let defaTest = test || getCheck[0].test;
  let sqlArrCheck = [defaName, defaPassword, defaTest, name];
  let getedit = await dbConfig.SySqlConnect(sql.editUserUpdateSQL, sqlArrCheck);
  if (getedit.hasOwnProperty("err")) return next(getedit);
  res.send({ user: getedit, msg: "修改成功" });
};

//获取用户信息
getInfo = async (req, res, next) => {
  let { name, password } = req.query;
  var sqlArr = [name, password];
  let getinfo = await dbConfig.SySqlConnect(sql.getInfoSelectNPSQL, sqlArr);
  // 查询访问量
  let statistics = await dbConfig.SySqlConnect(sql.getInfoSelectIdSQL);
  if (getinfo.hasOwnProperty("err") || statistics.hasOwnProperty("err"))
    return next(getinfo);
  res.send({
    user: getinfo.length > 0 ? getinfo : "用户名或密码是否正确？",
    statistics: statistics.length,
  });
};
//删除用户
deleteUser = async (req, res, next) => {
  let { name } = req.query;
  const deleteInSQL = sql.deleteUserInsertSQL;
  const deleteDeSQL = sql.deleteUserDeleteSQL;
  let replace_data = await dbConfig.SySqlConnect(deleteInSQL, [name]);
  let delete_data = await dbConfig.SySqlConnect(deleteDeSQL, [name]);
  if (replace_data.hasOwnProperty("err") || delete_data.hasOwnProperty("err"))
    return next(delete_data);
  if (!replace_data.insertId)
    return next({ msg: "删除用户出错", err: delete_data });
  res.send({ msg: "删除成功", info: delete_data, code: true });
  countRows--; //users_table行数-1
};
// 分页查询
paging = async (req, res, next) => {
  let { page, item } = req.query;
  item = item ? +item + 1 : 11;
  page = (page - 1) * (item - 1);
  if (isNaN(page)) return next({ msg: "参数错误" });
  const paging_data = await dbConfig.SySqlConnect(sql.pagingSQL, [page, item]);
  console.log("Query page and item", page / (item - 1) + 1, item - 1);
  if (paging_data.hasOwnProperty("err")) return next(paging_data);
  let nextPage = false;
  if (paging_data.length === item) {
    paging_data.pop();
    nextPage = true;
  }
  res.send({
    data: paging_data,
    nextPage, //true仍有下页数据;false无下页数据
    countRows,
  });
};

// jsonp跨域测试接口
jsonp = (req, res, next) => {
  let cbfn = req.query.callback;
  cbfn = `${cbfn}('jsonp跨域请求内容')`;
  console.log(cbfn);
  res.send(cbfn);
};
module.exports = {
  getCate, //默认输出 '/'
  getPostCate, //查看post表 根据id取值
  getInfo, //根据cate_id查看用户数据
  getCode, //发送验证码
  proveCode, //登录验证
  registered, //注册用户
  dropOut, //退出登录
  editUser, //查询或编辑用户数据
  deleteUser, //删除用户
  getFiles, //下载
  paging, //分页查询
  jsonp, //跨域测试
};
